let express = require("express");
let router = express.Router();
let infoService = require("../service/infoService.js");

let multiparty = require("multiparty");
let path = require("path");

router.get("/infoList", async function (req, res, next) {
  let {
    key,
    val,
    page,
    limit
  } = req.query;
  let filter = null;
  // console.log(val)
  //查询
  if (key != null) {
    if (key == "title") {
      filter = {
        "title": {
          $regex: new RegExp(val)
        }
      } //正则表达式 模糊查询
    }
  }
  if (!val) {
    filter = null;
  }

  let result = await infoService.infoList(filter, page, limit);
  res.send(result);
})

//获取图片
  router.post("/uploadinfo",(req, res) => {
    let imgPath = path.join(__dirname, "../public/images");
    //创建上传的form对象，需要指定上传保存文件的地址
    var form = new multiparty.Form({
      uploadDir: imgPath
    });

    form.parse(req, async function (err, fields, files) {
         console.log(fields)
      //得到传递过来的键值对参数的值
     let title= fields.title[0];
     let date=new Date(fields.date[0]);
     let comment=fields.textarea;

      // 遍历传递过来的键值对参数的值
      //Object.keys(fields).forEach(function(name) {
        // console.log(fields)
        //   console.log(fields[name]);
      //});
      
      //遍历传递过来的文件
      // Object.keys(files).forEach(function (name) {
      //   console.log(name)
      //   console.log(files[name]);
      // });
  
  
     
  
      //封装images字段格式
     let image=[];
      //err是回调函数中的错误对象，如果有值，就表示出现错误
      if (err) {
        res.send({
          code: -1,
          msg: "上传失败",
          data: err
        });
      } else {
        //没有错误，就读取上传文件
      //封装images字段格式      
        if(files.file){
          for(let i=0;i<files.file.length;i++){
            let obj={img: files.file[i].path.substring(
             files.file[i].path.indexOf("images")
           ),text:fields.text[i]};
           image.push(obj)
           } 
        }else{
          return;
        }

     
      } 
      //添加
      //把得到的数据传入数据库
      let data=await infoService.addInfo({title,date,image,comment});
     
    //   if(data._id){
    //   res.send({code:1,msg:"新增成功"})
    //   }else{
    //   res.send({code:-1,msg:"新增失败"})
    //   }
    });
  })

//删除
router.delete("/delinfo/:id", async (req, res, next) => {
  let id = req.params.id;
  let data = await infoService.deleteInfo(id);

  if (data.deletedCount > 0) {
    res.send({
      code: 1,
      msg: "删除成功"
    });
  } else {
    res.send({
      code: -1,
      msg: "删除失败"
    })
  }

})
//修改
router.put("/alter/:id", async (req, res, next) => {
  let id = req.params.id;
  let {
    title,
    date,
    image,
    comment
  } = req.body;
  let data = await infoService.alterInfo({
    id,
    title,
    date,
    image,
    comment
  });

  if (data.modifiedCount > 0) {
    res.send({
      code: 1,
      msg: "修改成功"
    })
  } else {
    res.send({
      code: -1,
      msg: "修改失败"
    })
  }

})

module.exports = router;